package com.tedu.egcar1.controller;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.tedu.egcar1.base.response.JsonResult;
import com.tedu.egcar1.base.response.StatusCode;
import com.tedu.egcar1.mapper.UserMapper;
import com.tedu.egcar1.pojo.dto.UserLoginParam;
import com.tedu.egcar1.pojo.dto.UserRegParam;
import com.tedu.egcar1.pojo.entity.User;
import com.tedu.egcar1.pojo.vo.UserVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@RestController
@RequestMapping("/v1/user")
@Tag(name = "用户模块")
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @PostMapping("/reg")
    @Operation(summary = "注册功能")
    @ApiOperationSupport(order = 10)
    public JsonResult insert(@RequestBody UserRegParam userRegParam){
        int num = userMapper.selectByUsername(userRegParam.getUsername());
        if (num > 0) {
            return new JsonResult(StatusCode.USERNAME_EXISTS);
        }
        User user = new User();
        BeanUtils.copyProperties(userRegParam,user);
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        userMapper.insert(user);
        return JsonResult.success();
    }
    @PostMapping("/login")
    @Operation(summary = "登录功能")
    @ApiOperationSupport(order = 20)
    public JsonResult login(@RequestBody UserLoginParam userLoginParam, HttpSession session){
        UserVO userVO = userMapper.select(userLoginParam);
        if (userVO ==null){
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }
        session.setAttribute("user",userVO);
        return JsonResult.success(userVO);
    }

    @GetMapping("/currentUser")
    @Operation(summary = "获取当前登录")
    @ApiOperationSupport(order=30)
    public JsonResult currentUser(HttpSession session){
        UserVO userVO = (UserVO) session.getAttribute("user");
        return JsonResult.success(userVO);
    }
    @GetMapping("/logout")
    @Operation(summary = "退出登录")
    @ApiOperationSupport(order = 40)
    public void logout(HttpSession session){
        session.removeAttribute("user");
    }

}
